package com.bobi.tfca.ui.mainnavigation.home.activity

import android.widget.ImageView
import android.widget.Toast
import androidx.lifecycle.ViewModel
import com.bobi.tfca.R
import com.bobi.tfca.network.ApiResponse
import com.bobi.tfca.network.api.ResourceAPI
import com.bobi.tfca.util.LogUtil
import com.bobi.tfca.viewmodel.PublicViewModel
import com.bumptech.glide.Glide
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MultipartBody

class OrgActivityFragmentVM: ViewModel() {

    fun uploadImageToServer(
        fragment: OrganizeActivityFragment,
        publicViewModel: PublicViewModel,
        file: MultipartBody.Part,
        imageView: ImageView
    ) {
        publicViewModel.apply {
            request(ResourceAPI::class.java).uploadImage(file).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                LogUtil.i("上传成功")
                                val url = it.data?.data
                                if (url != null && url.isNotBlank() && (!"null".equals(url))) {
                                    if (fragment.isAdded() && !fragment.isDetached()) {
                                        Glide.with(fragment).load(url).placeholder(R.drawable.defaultbg_h).into(imageView)
                                    }
                                    // 更改viewmodel的值
                                    publicViewModel.organizeActivity.outsidePicture = url
                                } else {
                                    Toast.makeText(fragment.requireActivity(), "图片上传失败", Toast.LENGTH_SHORT).show()
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}